package com.msgclient.ui;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

@SuppressLint("NewApi")
public class ConnectUI extends Activity {

	private TextView tv_ip = null;
	private Button btn_connect = null;
	private Button btn_disconnect = null;
	private Socket socket;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_connect);

		tv_ip = (EditText) findViewById(R.id.ip);
		btn_connect = (Button) findViewById(R.id.connect);
		btn_disconnect = (Button) findViewById(R.id.disconnect);
		btn_disconnect.setEnabled(false);
		btn_connect.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				ConnectTask task = new ConnectTask();
				task.execute(100);
			}

		});

		btn_disconnect.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					if (socket != null && socket.isConnected()) {
						socket.close();
						Log.i("ok", "关闭socket");
						btn_connect.setText("连    接...");
						btn_connect.setEnabled(true);
						btn_disconnect.setEnabled(false);
					}
				} catch (IOException e) {
					Log.e("关闭socket异常", e.toString());
				}
			}

		});

	}

	
	@Override
	protected void onStop() {
		super.onStop();
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.e("stop", "stop");
	}
	class ConnectTask extends AsyncTask<Integer, String, String> {

		@Override
		protected String doInBackground(Integer... params) {
			try {
				String ipAndPort = tv_ip.getText().toString().trim();
				String[] socketStr = ipAndPort.split(":");
				SocketAddress socAddress = new InetSocketAddress(
						InetAddress.getByName(socketStr[0]),
						Integer.parseInt(socketStr[1]));
				socket = new Socket();
				socket.connect(socAddress);
			} catch (IOException ex) {
				ex.printStackTrace();
				Log.d("", ex.toString());
			}
			 publishProgress("连接成功...");
			return "ok";
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			btn_connect.setText(values[0]);
			btn_connect.setEnabled(false);
			btn_disconnect.setEnabled(true);
			super.onProgressUpdate(values);
		}

	}

}
